package com.lindroy.androidplayer.ui.dialog

import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.lindroy.androidplayer.R
import com.lindroy.lib_utils.extensions.getResColor
import com.lindroy.lib_utils.extensions.getResString
import com.lindroy.lib_utils.extensions.shortToast

/**
 * @author Lin
 * @date 2022/3/1
 * @function
 */

private typealias OnButtonClickListener = (dialog: DialogInterface) -> Unit

class ComDialog : DialogFragment() {
    private var title = ""
    private var message = ""
    private var positiveListener: OnButtonClickListener? = null
    private var negativeListener: OnButtonClickListener? = null

    override fun onCreateDialog(savedInstanceState: Bundle?) =
        MaterialAlertDialogBuilder(requireContext())
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton(R.string.confirm) { dialog, which ->
                positiveListener?.invoke(dialog)
            }
            .setNegativeButton(R.string.cancel) { dialog, which ->
                negativeListener?.invoke(dialog)
            }
            .create().also { md ->
                md.setOnShowListener {
                    md.getButton(AlertDialog.BUTTON_NEGATIVE)
                        .setTextColor(getResColor(R.color.text_gray))
                }
            }

    fun setTitle(@StringRes stringId: Int) = this.apply { title = getResString(stringId) }

    fun setMessage(@StringRes stringId: Int) = this.apply { message = getResString(stringId) }

    fun setOnPositiveClickListener(listener: OnButtonClickListener) = this.apply {
        positiveListener = listener
    }

    fun setOnNegativeClickListener(listener: OnButtonClickListener) = this.apply {
        negativeListener = listener
    }

    fun show(fm: FragmentManager) {
        show(fm, this::javaClass.name)
    }

    companion object {
        fun create() = ComDialog()
    }

}